#include "plotwidget.h"
#include "functioneditorwidget.h"
#include "plotView.h"
#include "functionsmodel.h"
#include "functionedit.h"
#include "functionsView.h"
#include <QPushbutton>

PlotWidget::PlotWidget():QSplitter()
{
    b_funcsModel = new FunctionsModel(this);
    editor = new FunctionEditorWidget(b_funcsModel,this);
    plotView = new PlotView(b_funcsModel,this);
    plotView->setBackgroundRole(QPalette::BrightText);
    editor->setFixedWidth(250);
    addWidget(plotView);
    addWidget(editor);
    connect(editor->getFunctionEdit(),SIGNAL(accept()),this,SLOT(new_func()));
    connect(editor->getFuncsView(), SIGNAL(clicked(const QModelIndex &)), this, SLOT(edit_func(const QModelIndex &)));
    connect(editor->getOk(),SIGNAL(clicked()),this,SLOT(create_func()));
    connect(editor->getDeleteButton(),SIGNAL(clicked()),this, SLOT(deleteFunc()));
}
void PlotWidget::new_func()
{
    FunctionEdit* funced = editor->getFunctionEdit();
    QString name = funced->name();
    function f(funced->name(), Expression(funced->text(), funced->isMathML()), funced->color());

    if(funced->editing()) {

        b_funcsModel->editFunction(name, f);
    }
    else {
        b_funcsModel->addFunction(f);

    }
    funced->setEditing(true);
    b_funcsModel->setSelected(name);
    plotView->setFocus();
}

void PlotWidget::edit_func(const QModelIndex &idx)
{
    editor->getDeleteButton()->setEnabled(true);
    FunctionEdit *funced = editor->getFunctionEdit();
    funced->setName(b_funcsModel->data(idx.sibling(idx.row(), 0)).toString());
    funced->setText(b_funcsModel->data(idx.sibling(idx.row(), 1)).toString());
    funced->setColor(b_funcsModel->data(idx.sibling(idx.row(), 0),Qt::UserRole+3).value<QColor>());
    funced->setEditing(true);
    editor->getStackedWidget()->setCurrentIndex(1);
    funced->setFocus();

}

void PlotWidget::create_func()
{
    FunctionEdit * b_funced = editor->getFunctionEdit();
    b_funced->setName(QString("f").append(QString::number(b_funcsModel->rowCount()+1)));
    b_funced->setText("0");
    b_funced->setEditing(false);
    editor->getStackedWidget()->setCurrentIndex(1);
    b_funced->setFocus();
}

void PlotWidget::deleteFunc()
{
    b_funcsModel->removeRow(b_funcsModel->getSelectedRow());
    editor->getStackedWidget()->setCurrentIndex(0);
}

void PlotWidget::setStackedWidget(int i)
{
    editor->getStackedWidget()->setCurrentIndex(i);
}

void PlotWidget::exportToImage()
{
    QString path = QFileDialog::getSaveFileName(this, tr("Export to image"),
                            "./untitled.png",
                            tr("Image File(*.png)\n SVG File(*.svg)"));
    if(!path.isEmpty())
                plotView->toImage(path);
}
